package ${packagePath}.common.ext;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ${packagePath}.model.to.ResultTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice("${packagePath}.controller")
@Slf4j
public class ResponseResultBodyAdvice implements ResponseBodyAdvice<Object> {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 所有方法都统一返回，如果要根据自定义注解来返回，则采用：
     * return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ANNOTATION_TYPE) || returnType.hasMethodAnnotation(ANNOTATION_TYPE);
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 当类或者方法使用了就会调用这个方法
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        // 防止重复包裹的问题出现
        if (body instanceof ResultTo || body instanceof ModelAndView) {
            return body;
        } else if (body instanceof String) {
            try {
                return mapper.writeValueAsString(ResultTo.success(body));
            } catch (JsonProcessingException e) {
                log.error("beforeBodyWrite解析JSON异常", e);
            }
        }
        return ResultTo.success(body);
    }
}
